package com.hclc.util.poi;

import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellType;
import org.apache.poi.xwpf.extractor.XWPFWordExtractor;
import org.apache.poi.xwpf.usermodel.XWPFDocument;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.DecimalFormat;
import java.util.Objects;

/**
 * @Author: hef
 * 文件工具类
 * @Date: Create in 11:18 2019-09-27
 */
public class PoiUtil {

    /**
     * docx格式
     *
     * @param fs
     * @return java.lang.String
     * @author hef
     * @version 1.0
     * @date 2019-09-27 11:22
     */
    public static String docxString(InputStream fs) throws IOException {
        StringBuilder result = new StringBuilder();
        XWPFDocument docx = new XWPFDocument(fs);
        XWPFWordExtractor re = new XWPFWordExtractor(docx);

        result.append(re.getText());
        re.close();
        return result.toString();
    }

    /**
     * docx格式
     *
     * @param file
     * @return java.lang.String
     * @author hef
     * @version 1.0
     * @date 2019-09-27 11:22
     */
    public static String docxString(File file) throws IOException {
        return docxString(new FileInputStream(file));
    }

    /**
     * 格式化excel值
     *
     * @param hssfCell
     * @return java.lang.String
     * @author yurj
     * @mail 1638234804@qq.com
     * @version 1.0
     * @date 2019-12-1 8:40
     */

    public static String getValue(Cell hssfCell) {
        if (hssfCell.getCellType() == CellType.BOOLEAN) {
            // 返回布尔类型的值
            return String.valueOf(hssfCell.getBooleanCellValue());
        } else if (hssfCell.getCellType() == CellType.NUMERIC) {
            // 返回数值类型的值
            Object inputValue = null;// 单元格值
            Long longVal = Math.round(hssfCell.getNumericCellValue());
            Double doubleVal = hssfCell.getNumericCellValue();
            if (Objects.equals(Double.parseDouble(longVal + ".0"), doubleVal)) {   //判断是否含有小数位.0
                inputValue = longVal;
            } else {
                inputValue = doubleVal;
            }
            DecimalFormat df = new DecimalFormat("#.####");    //格式化为四位小数，按自己需求选择；
            return String.valueOf(df.format(inputValue));      //返回String类型
        } else {
            // 返回字符串类型的值
            return String.valueOf(hssfCell.getStringCellValue());
        }
    }
}
